<template>
  <el-card ref="wrapper" :body-style="{ padding: 0 }">
    <v-stage :config="stageConfig" @mousedown="mousedown" @mousemove="mousemove" @mouseup="mouseup">
      <v-layer>
        <v-line v-for="(line ,index) in lines" :key="index" :config="line" />
      </v-layer>
    </v-stage>
  </el-card>
</template>

<script>
import common from '@/util/common'
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'
export default {
  data() {
    return {
      // 画布配置
      stageConfig: {
        width: 800,
        height: 700
      },
      // 绘画状态
      painting: false,
      stroke: '#df4b26',
      strokeWidth: 3
    }
  },

  computed: {
    ...mapState(['lines']),
    ...mapGetters(['isGameStarted'])
  },

  mounted() {
    // 将画布的宽度设置成与容器同宽
    this.stageConfig.width = this.$refs.wrapper.$el.offsetWidth
  },

  methods: {

    ...mapMutations(['drawNewLine', 'updateLine']),
    ...mapActions(['sendDrawNewLine', 'sendUpdateNewLine']),

    showGameNotice() {
      this.$message({
          type: 'warning',
          message: '游戏未开始！'
      })
    },

    // 鼠标按下事件
    mousedown(e) {

      // 判断游戏是否开始
      if (!this.isGameStarted) {
        //common.throttle(this.showGameNotice, 500)
        this.showGameNotice()
        return
      }

      this.painting = true

      // 创建一个新线条
      let newLine = {
        stroke: this.stroke, // 线条颜色
        strokeWidth: this.strokeWidth, // 线条宽度
        points: [e.evt.layerX, e.evt.layerY] // 线条起点坐标
      }

      // 本地画线，存储到vuex
      this.drawNewLine(newLine)
      
      // 请求服务端
      this.sendDrawNewLine(newLine)
      
    },
    // 鼠标拖动事件
    mousemove(e) {

      if (!this.painting) {
        return
      }

      let lastLine = this.lines[this.lines.length - 1]
      lastLine.points = lastLine.points.concat([e.evt.layerX, e.evt.layerY])
      
      // 更新本地画线，存储到vuex
      this.updateLine(lastLine)
      
      // 请求服务端
      this.sendUpdateNewLine(lastLine)
    },

    // 鼠标释放事件
    mouseup(e) {
      this.painting = false
    }
  }
}
</script>